package com.android.bookgarden.utli;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.cardemulation.CardEmulation;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import static android.content.Context.TELEPHONY_SERVICE;

public class AppUtils {

    private static final String TAG = "AppUtils";
    private static boolean downFlag = true;
//    private static String appChannel;

    /**
     * 安装应用
     *
     * @param context
     * @param fileName
     */
    public static void installApk(Context context, String fileName) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + fileName), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }


    /**
     * 卸载应用
     *
     * @param context
     * @param packageName
     */
    public static void uninstall(Context context, String packageName) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + packageName));
        context.startActivity(intent);
    }

    /**
     * 获取应用版本号
     *
     * @param context
     * @param packageName
     * @return
     */
    public static String getAppVersion(Context context, String packageName) {

        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            // 当前应用的版本名称
            System.out.println("应用本身版本" + info);
            return info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 应用是否需要更新
     *
     * @param context
     * @param packageName
     * @param versionName
     * @return
     */
    public static boolean getAppNeedUpdate(Context context, String packageName, String versionName) {

        if (versionName == null || versionName.equals(""))
            return true;

        return !versionName.equals(getAppVersion(context, packageName));
    }


    /**
     * 根据获取系统中是否已安装应用
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isInstallApk(Context context, String packageName) {
        boolean install = false;
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                if (packageInfo.packageName.equals(packageName)) {
                    install = true;
                    break;
                }
            }
        }
        return install;
    }

    /**
     * 获取当前版本号
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }






    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }





    /**
     * 下载新版本程序，需要子线程
     */
    public static void loadNewVersionProgress(final Context context, String url) {
//        final   String uri="http://www.apk.anzhi.com/data3/apk/201703/14/4636d7fce23c9460587d602b9dc20714_88002100.apk";
        final String uri = url;
        final ProgressDialog progressDialog;    //进度条对话框
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("下载中,请稍后......");
        progressDialog.setCancelable(false);

        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //对话框消失,下载中断
                downFlag = false;
            }
        });

//        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
//            @Override
//            public void onCancel(DialogInterface dialog) {
//                //对话框消失,下载中断
//                downFlag=false;
//            }
//        });

        progressDialog.show();
        //启动子线程下载任务
        //**********8

//        long time = System.currentTimeMillis();//当前时间的毫秒数
//        File externalStorageDirectory = Environment.getExternalStorageDirectory();
//        String fileName=externalStorageDirectory.getName()+time + "updata.apk";
//        OkGo.<File>post(url).execute(new FileCallback(fileName) {
//            @Override
//            public void onSuccess(Response<File> response) {
//                installApk(context,response);
//            }
//        });
//        ************

        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(uri, progressDialog);
                    sleep(3000);
                    installApk(context, file);
                    progressDialog.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    //下载apk失败
                    Toast.makeText(context.getApplicationContext(), "下载新版本失败", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 从服务器获取apk文件的代码
     * 传入网址uri，进度条对象即可获得一个File文件
     * （要在子线程中执行哦）
     */
    public static File getFileFromServer(String uri, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(uri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            long time = System.currentTimeMillis();//当前时间的毫秒数
            File file = new File(Environment.getExternalStorageDirectory(), time + "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len = bis.read(buffer);
            int total = 0;
            do {
                fos.write(buffer, 0, len);
                total += len;
////                获取当前下载量
                pd.setProgress(total);
                pd.setProgress(total);

            } while ((len = bis.read(buffer)) != -1 && downFlag);

//            while ((len = bis.read(buffer)) != -1) {
//                fos.write(buffer, 0, len);
////                total+= len;
////                获取当前下载量
////                pd.setProgress(total);
//            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * 安装apk
     */
    protected static void installApk(Context context, File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }







    public static String getAppChannel(Context context) {
        String appChannel = "";
        ApplicationInfo appInfo = null;
        try {
            appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            appChannel = appInfo.metaData.getString("APP_CHANNEL");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return appChannel;
    }
}
